﻿using UnityEngine;
using System.Collections.Generic;
using System;

namespace SSAAD {
	class JMPScienceComms : PartModule {
		[KSPField]
		public bool on;

		[KSPField]
		public float dataRate = 0;

		[KSPField]
		public float electricCost = 0;

		public void FixedUpdate() {
			if (part.isControllable && on) {
				List<JMPScienceStorageModule> scienceMods = new List<JMPScienceStorageModule>();

				float dataAvailable = 0;
				foreach (JMPScienceStorageModule s in vessel.FindPartModulesImplementing<JMPScienceStorageModule>()) {
					dataAvailable += s.capacityUsed;
					if (s.capacityUsed > 0) { scienceMods.Add(s); }
				}

				if (scienceMods.Count <= 0 || dataAvailable <= 0) { return; }

				float dataRatio = Mathf.Min(dataAvailable / (dataRate * TimeWarp.CurrentRate), 1.0f);
				float powerCost = electricCost * dataRatio * TimeWarp.CurrentRate;
				float power = part.RequestResource("ElectricCharge", powerCost);
				float ratio = 1;
				if (electricCost > 0) { ratio = power / powerCost; }
				float dataSent = ratio * dataRate * dataRatio * TimeWarp.CurrentRate;

				if (dataSent > 0) {
					foreach (JMPScienceStorageModule s in scienceMods) {
						dataSent = s.transmitHome(dataSent);
						if (dataSent <= 0) { break; }
					}
				}
			}
		}

		[KSPEvent(guiActive = true, guiName = "Activate")]
		public void Activate() {
			Events["Deactivate"].active = true;
			Events["Activate"].active = false;
			on = true;
		}

		[KSPEvent(guiActive = true, guiName = "Deactivate")]
		public void Deactivate() {
			Events["Deactivate"].active = false;
			Events["Activate"].active = true;
			on = false;
		}

		public override void OnLoad(ConfigNode node) {
			if (on) { Activate(); }
			else { Deactivate(); }
		}

		public static void FixedBackgroundUpdate(Vessel v, uint id) {
		}

		public static void FixedBackgroundUpdate(Vessel v, uint id, Func<Vessel, float, string, float> resourceRequest) {
		}
	}
}
